package com.googlecode.jvmpart.utils;

import java.io.File;
import java.io.IOException;

public class KillProcess {
	public static void main(String[] args) {
		if (args.length < 1)
			throw new IllegalArgumentException("Request a PID");
		String pid = args[0];
		File f = new File(pid);
		if(!f.exists()) {
			System.out.println("process unfound:"+pid);
			return;
		}
		try {
			int exitCode = kill(pid).waitFor();
			checkExitCode(pid, exitCode);
			String[] childPIDs = f.list();
			Process[] processes = new Process[childPIDs.length];
			for(int i=0;i<childPIDs.length;i++) {
				processes[i] = kill(childPIDs[i]);
			}
			for(int j=0;j<processes.length;j++) {
				exitCode = processes[j].waitFor();
				checkExitCode(childPIDs[j], exitCode);
				if(exitCode==0) new File(f, childPIDs[j]).delete();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			f.delete();
		}
	}
	private static void checkExitCode(String pid, int exitCode) {
		if(exitCode!=0)
			System.out.println("kill "+pid+" exitcode:"+exitCode);
		else
			System.out.println(pid+" killed!");
	}
	public static Process kill(String pid) throws IOException {
		Runtime rt = Runtime.getRuntime();
		String command = null;
		if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1)
			command = "ntsd -c q -p " + pid;
		else
			command = "kill -9 " + pid;
		System.out.println(command);
		return rt.exec(command);		
	}
}
